class Blog < ActiveRecord::Base
  # validates_presence_of
  validates :content, :title, :presence=>{:message=>"不能为空"}

  belongs_to :user, :class_name=>"DeviseUser" # 这个类名称呢，不能使用devise_user,而应该使用真正的类名！所以说，有时候真的会让人迷糊！
  has_and_belongs_to_many :categories

  scope :sorted, lambda {order("created_at desc")}
  scope :visible, lambda { where(:visible=>true) }
  scope :hiding, lambda { where(:visible=>false) }
  scope :no_user, lambda { where(:user=>nil) }
  scope :recent, lambda{where(:created_at=>1.days.ago..Time.now)}
  scope :recent_one, lambda{where(:created_at=>1.days.ago..Time.now).limit 1}
  scope :search, lambda { |query| where(["title like ?","%#{query}%"]) }

  def long_title
    "#{title}==#{content}"
  end

  def editable_by?(current_user)
    # 一定需要前面一个，不然，当你没有使用用户显示Blog.all的时候
    current_user && user==current_user
  end

  def join!(category)
    categories << category
  end

  def quit!(category)
    categories.delete(category)
  end
end
